#include "qopenharmonycamerasession.h"

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QList<OPenHarmonyCameraInfo>, g_availableCameras)

QOPenHarmonyCameraSession::QOPenHarmonyCameraSession(QObject *parent) : QObject{ parent }
    , m_camera(Q_NULLPTR)
    , m_captureMode(QCamera::CaptureStillImage)
    , m_state(QCamera::UnloadedState)
{

}

QOPenHarmonyCameraSession::~QOPenHarmonyCameraSession()
{

}

const QList<OPenHarmonyCameraInfo> &QOPenHarmonyCameraSession::availableCameras()
{    
    if (g_availableCameras->isEmpty())
        updateAvailableCameras();

    return *g_availableCameras;
}

void QOPenHarmonyCameraSession::setState(QCamera::State state)
{

}

void QOPenHarmonyCameraSession::setStateHelper(QCamera::State state)
{
    switch (state) {
    case QCamera::UnloadedState:
        close();
        break;
    case QCamera::LoadedState:
    case QCamera::ActiveState:
        if (!m_camera && !open()) {
            m_state = QCamera::UnloadedState;
            emit stateChanged(m_state);
            emit error(QCamera::CameraError, QStringLiteral("Failed to open camera"));
            m_status = QCamera::UnloadedStatus;
            emit statusChanged(m_status);
            return;
        }
        if (state == QCamera::ActiveState)
            startPreview();
        else if (state == QCamera::LoadedState)
            stopPreview();
        break;
    }
}


void QOPenHarmonyCameraSession::setCaptureMode(QCamera::CaptureModes mode)
{

}

bool QOPenHarmonyCameraSession::isCaptureModeSupported(QCamera::CaptureModes mode) const
{

}

void QOPenHarmonyCameraSession::onApplicationStateChanged(Qt::ApplicationState state)
{
    switch (state) {
    case Qt::ApplicationInactive:
        if (m_state != QCamera::UnloadedState) {
            m_savedState = m_state;
            //close(); TODO
            m_state = QCamera::UnloadedState;
            emit stateChanged(m_state);
        }
        break;
    case Qt::ApplicationActive:
        if (m_savedState != -1) {
            setStateHelper(QCamera::State(m_savedState));
            m_savedState = -1;
        }
        break;
    default:
        break;
    }
}

void QOPenHarmonyCameraSession::updateAvailableCameras()
{    
    g_availableCameras->clear();

    const QStringList &ids = OPenHarmonyCamera::getIdOfCameras();
    for (const QString &id : qAsConst(ids)) {
        OPenHarmonyCameraInfo info;
        OPenHarmonyCamera::getCameraInfo(id, &info);

        if (!info.name.isNull())
            g_availableCameras->append(info);
    }
}

bool QOPenHarmonyCameraSession::open()
{
    return false;
}

void QOPenHarmonyCameraSession::close()
{

}

bool QOPenHarmonyCameraSession::startPreview()
{
    return false;
}

void QOPenHarmonyCameraSession::stopPreview()
{

}

QT_END_NAMESPACE
